package ansible

import (
	"context"
	"log/slog"
	"os"
)

// Logger 是一个结构化日志记录器的包装器
type Logger struct {
	*slog.Logger
}

// NewLogger 创建一个新的结构化日志记录器
func NewLogger(level slog.Level) *Logger {
	opts := &slog.HandlerOptions{
		Level: level,
	}
	handler := slog.NewTextHandler(os.Stderr, opts)
	return &Logger{
		Logger: slog.New(handler),
	}
}

// NewJSONLogger 创建一个 JSON 格式的日志记录器
func NewJSONLogger(level slog.Level) *Logger {
	opts := &slog.HandlerOptions{
		Level: level,
	}
	handler := slog.NewJSONHandler(os.Stderr, opts)
	return &Logger{
		Logger: slog.New(handler),
	}
}

// LogCommand 记录命令执行信息
func (l *Logger) LogCommand(ctx context.Context, command string, args []string) {
	l.InfoContext(ctx, "executing ansible command",
		slog.String("command", command),
		slog.Any("args", args),
	)
}

// LogCommandResult 记录命令执行结果
func (l *Logger) LogCommandResult(ctx context.Context, command string, success bool, duration string, err error) {
	if success {
		l.InfoContext(ctx, "command completed successfully",
			slog.String("command", command),
			slog.String("duration", duration),
		)
	} else {
		l.ErrorContext(ctx, "command failed",
			slog.String("command", command),
			slog.String("duration", duration),
			slog.Any("error", err),
		)
	}
}

// LogInventoryOperation 记录 inventory 操作
func (l *Logger) LogInventoryOperation(ctx context.Context, operation string, details map[string]any) {
	l.InfoContext(ctx, "inventory operation",
		slog.String("operation", operation),
		slog.Any("details", details),
	)
}

// 默认日志记录器实例
var defaultLogger = NewLogger(slog.LevelInfo)

// SetDefaultLogger 设置默认日志记录器
func SetDefaultLogger(logger *Logger) {
	defaultLogger = logger
}

// GetDefaultLogger 获取默认日志记录器
func GetDefaultLogger() *Logger {
	return defaultLogger
}
